package top.txl.controller;

import io.jsonwebtoken.Claims;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import top.txl.entity.Employee;
import top.txl.entity.PageBean;
import top.txl.entity.R;
import top.txl.service.EmployeeService;
import top.txl.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest httpServletRequest, @RequestBody Employee employee) {
        /**
         *
         * 1、将页面提交的密码password进行md5加密处理
         * 2、根据页面提交的用户名username查询数据库
         * 3、如果没有查询到则返回登灵失败结果
         * 4、密码比对，如果不一致则返回登录失败结果
         * 5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
         * 6、登录成功，将员工id存入Session并返回登录成功结果
         *
         */
        //  1、将页面提交的密码password进行md5加密处理
        log.info("login");
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 2、根据页面提交的用户名username查询数据库
        Employee emp = employeeService.admin(employee);

        // 3、如果没有查询到则返回登灵失败结果
        if (emp == null) {
            return R.error("登录失败");
        }
        // 4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        //  5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已经禁用，请联系管理员");
        }


        // 6、登录成功，将员工id存入Session并返回登录成功结果
        httpServletRequest.getSession().setAttribute("employee", emp.getId());
        HashMap<String, Object> claim = new HashMap<>();
        claim.put("id", emp.getId());
        claim.put("username", emp.getUsername());
        String jwt = JwtUtils.createJwt(claim);
        emp.setJWT(jwt);
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest serve) {
        log.info("退出登录");
        // 清除 sessionid
        serve.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @GetMapping("/lists")
    public R<PageBean> lists(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             String keyWords) {
        log.info("获取数据");
        PageBean pageBean = employeeService.lists(page, pageSize, keyWords);
        return R.success(pageBean);
    }

    @PostMapping("/lists")
    public R<String> add(HttpServletRequest request,@RequestBody Employee employee){
        log.info("添加用户");
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        // 设置初始密码
        employee.setPassword(password);

        // 获取当前用户
        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJwt(jwt);
        Object id = claims.get("id");
        // 设置谁操作
        employee.setUpdateUser((Integer) id);
        employee.setCreateUser((Integer)id);

        employeeService.add(employee);
        return R.success("添加成功");
    }

    @PutMapping("/lists")
    public R<String> update(@RequestBody Employee employee){
        log.info("更新");
        employee.setUpdateTime(LocalDateTime.now());
        employeeService.update(employee);
        return R.success("更新成功");
    }

    @DeleteMapping("/lists/{id}")
    public R<String> delete(@PathVariable Integer id){
        log.info("删除");
        if(id == null){
            return R.error("参数错误");
        }
        employeeService.delete(id);
        return R.success("操作成功");
    }

    @GetMapping("/lists/{id}")
    public R<Employee> getDetail(@PathVariable Integer id){
        log.info("用户详情信息",id);
        if(id == null){
            return R.error("参数错误");
        }
        Employee emp  = employeeService.detail(id);
        return R.success(emp);
    }

//    @PutMapping("/updateStatus")
//    public R<String> updateStatus(@RequestBody Employee emp){
//        log.info("更新状态");
//        log.info("id,{},status,{}",emp.getStatus(),emp.getId());
//        employeeService.updateStatus(emp);
//        return R.success("更新成功");
//    }
}
